<template>
  <div>
    <div class='tinymce'>
      <h1>tinymce</h1>
      <editor
        id='tinymce'
        v-model='tinymceHtml'
        :init='init'
      ></editor>
    </div>
    <button @click="get">get</button>
    <button @click="put">put</button>
  </div>
</template>

<script>
import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/silver/theme'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/icons/default/icons.min.js'
import 'tinymce/themes/silver'
import 'tinymce/plugins/image'// 插入上传图片插件
import 'tinymce/plugins/media'// 插入视频插件
import 'tinymce/plugins/table'// 插入表格插件
import 'tinymce/plugins/link' //超链接插件
import 'tinymce/plugins/code' //代码块插件
import 'tinymce/plugins/lists'// 列表插件
import 'tinymce/plugins/contextmenu'  //右键菜单插件
import 'tinymce/plugins/wordcount' // 字数统计插件
import 'tinymce/plugins/colorpicker' //选择颜色插件
import 'tinymce/plugins/textcolor'  //文本颜色插件
import 'tinymce/plugins/fullscreen' //全屏
import 'tinymce/plugins/help'
import 'tinymce/plugins/charmap'
import 'tinymce/plugins/paste'
import 'tinymce/plugins/hr'
import 'tinymce/plugins/searchreplace'
import 'tinymce/plugins/insertdatetime'
import 'tinymce/plugins/toc'
import 'tinymce/plugins/codesample'
export default {
  name: 'tinymce',
  data: () => ({
    tinymceHtml: '请输入内容',
    init: {
      automatic_uploads: false,
      paste_data_images: true, // 允许粘贴图像
      menubar: false,  // 隐藏最上方menu
      statusbar: false, // 隐藏编辑器底部的状态栏
      language_url: '/tinymce/zh_CN.js',
      language: 'zh_CN',
      skin_url: '/tinymce/skins/ui/oxide',
      height: 800,
      toolbar: ['bold italic underline bullist numlist strikethrough blockquote hr|forecolor backcolor|formatselect |fontsizeselect  | alignleft aligncenter alignright alignjustify | image table |codeformat blockformats| removeformat searchreplace fullscreen help |undo redo'],
      plugins: 'lists image media table wordcount code fullscreen help codesample toc insertdatetime  searchreplace  link charmap paste hr',
      branding: false,
      images_upload_handler: function (blobInfo) {
        console.log(blobInfo.filename())
      },
      setup: function (ed) {
        ed.on('keyup', function () {
          const msg = tinymce.activeEditor.getContent()
          this.currentText = msg
          if (this.ws.readyState === 1 && this.new === false) {
            this.ws.send(msg)
          }
        }); ed.on(('change')=> {
        
          const msg = tinymce.activeEditor.getContent()
          this.currentText = msg
          if(this.ws.readyState === 1 && this.new === false) {
          this.ws.send(msg)
        }
      
    });
  }
    },
editorText: '',
  currentText: '',
    ws: null,
      new: true, // 初始页面的时候不向ws发送请求
        timeout: 28 * 10000, //  300秒一次心跳
          timeoutObj: null //  心跳倒计时
  }),
mounted() {
  tinymce.init({})
  this.initWebSocket()
},
components: { Editor },
methods: {
  get() {
    console.log(tinymce.activeEditor.getContent());
  },
  async put() {
    const html = tinymce.activeEditor.getContent()
    const data = {
      title: '时序预测',
      comment: html,
      updateName: 'cth'
    }
    await this.$http.puthtml(data)
  },
  async set() {
    const html = await this.$http.gethtml('时序预测')
    tinymce.activeEditor.setContent(html.data.comment)
  },
  initWebSocket() {
    const wsurl =
      'wss://dip.wanyol.com/websocket/' + '时序预测' + '/' + 'cth'
    this.ws = new WebSocket(wsurl)
    this.ws.onmessage = this.handleWsMessage
    this.ws.onopen = this.handleWsOpen
    this.ws.onerror = this.handleWsError
    this.ws.onclose = this.handleWsClose
  },
  async handleWsOpen(e) {
    console.log('FE: Websoket Open', e)
    this.set()
    this.start()
  },
  handleWsClose(e) {
    console.log('FE: Websoket Close', e)
  },
  handleWsError() {
    this.initWebSocket() // 连接建立失败重连
  },
  handleWsMessage(e) {
    try {
      const msg = JSON.parse(e.data)
      console.log(msg);
      this.$store.state.userlist = msg.userList
      setTimeout(() => {
        if (this.currentText !== msg.message) {
          tinymce.activeEditor.setContent('setHtml', msg.message)
        }
      }, 200)
    } catch (error) {
      return
    }
    this.reset()
  },
  reset() {
    //  重置心跳

    //  清除时间（清除心跳计时）
    clearInterval(this.timeoutObj)
    //  重启心跳
    this.start()
  },
  start() {
    //  开启心跳
    var self = this
    this.timeoutObj && clearInterval(this.timeoutObj)
    // 如果心跳倒计时存在的话，清除掉
    this.timeoutObj = setInterval(function () {
      // 重新赋值重新发送 进行心跳检测
      //  给后端发送心跳信息
      if (self.ws.readyState === 1) {
        //  如果连接正常
        self.ws.send('heartCheck')
      } else {
        //  否则重连
        // self.reconnect()
      }
    }, self.timeout)
  },
}
}
</script>